package cn.lzd.mr.case10;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 2019/7/16
 * 看第1列数据和其它第1列数据是否有重合，有重合就合并
 */
public class Case10MR4 {


    static class Mp extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String str = value.toString();
            String[] split = str.trim().split(",", -1);
            Arrays.sort(split);

            StringBuffer bf = new StringBuffer();

            for (String s : split) {
                bf.append(s).append(",");
            }
            String bs = bf.toString();
            bs = bs.substring(0, bs.length() - 1);

            context.write(new Text(bs), new Text(bs));

        }
    }

    static class Rd extends Reducer<Text, Text, Text, NullWritable> {

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            Set<String> sets = new HashSet<>();

            StringBuffer bf = new StringBuffer();
            for (Text value : values) {
                String[] split = value.toString().split(",");
                for (String s : split) {
                    sets.add(s);
                }
            }

            sets.stream().sorted(String::compareTo).forEach((x) -> bf.append(x).append(","));
            String bs = bf.toString();
            bs = bs.substring(0, bs.length() - 1);
            context.write(new Text(bs), NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception {

        String inpath = PathUtil.getpath("case10") + "/*";
        String outpath = PathUtil.getpath("case10") + "out2/";

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);
        job.setJarByClass(Case10MR4.class);

        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        job.setGroupingComparatorClass(GroupComparator10.class);

        FileInputFormat.addInputPath(job, new Path(inpath));
        FileOutputFormat.setOutputPath(job, new Path(outpath));

        job.waitForCompletion(true);

    }
}
